import * as open from 'open';
import * as vscode from 'vscode';
import { DataType } from '../ApiTreeDataProvider';
import { AnyChecker } from '../helper/AnyChecker';
import { QuickPick } from '../helper/QuickPick';
import { Memory } from '../memory';
import { fetchApiList } from './fetchApiList';
import { getConfig, getUsers } from '../configuration';

export namespace OpenApiDoc {
  export async function getDocItemFormAny(any: any): Promise<Memory.IDoc> {
    if (any === undefined) {
      return OpenApiDoc.pickDoc();
    }

    if (AnyChecker.apiTreeData(any, DataType.api)) {
      return any.data;
    }

    let ret = await AnyChecker.apiFileUri(any).then(v => v?.doc);
    if (ret) { return ret; }
    vscode.window.showErrorMessage('不是有效的TAV接口文件代码');
    throw new Error("不是有效的接口文件代码");
  }

  export async function getDocItemFormAny2(any: any): Promise<Memory.IDoc> {
    if (any === undefined) {
      return OpenApiDoc.pickDoc2();
    }

    if (AnyChecker.apiTreeData(any, DataType.api)) {
      return any.data;
    }

    let ret = await AnyChecker.apiFileUri(any).then(v => v?.doc);
    if (ret) { return ret; }
    vscode.window.showErrorMessage('不是有效的TAV接口文件代码');
    throw new Error("不是有效的接口文件代码");
  }


  export async function pickDoc() {
    if (!Memory.fullDocList.length) {
      await fetchApiList();
    }
    return await QuickPick
      .show(Memory.fullDocList, v => `${v.projectName}/${v.moduleName}/${v.name}(${v.httpMethod}) ${v.url}`)
      .then(idx => Memory.fullDocList[idx]);
  }

  export async function pickDoc2() {
    if (!Memory.fullDocList.length) {
      await fetchApiList();
    }

    const users = await getUsers();
    const user = await QuickPick
      .show(users, v => `${v.username}(${v.type})`)
      .then(idx => users[idx]);

    const spaces = Memory.list('space', user)!;
    const space = await QuickPick
      .show(spaces, v => `${v.name}(${v.id})`)
      .then(idx => spaces[idx]);

    const projects = Memory.list('project', user)?.filter(v => v.spaceId === space.id)!;
    const project = await QuickPick
      .show(projects, v => `${v.name}(${v.id})`)
      .then(idx => projects[idx]);

    const modules = Memory.list('module', user)?.filter(v => v.projectId === project.id)!;
    const module = await QuickPick
      .show(modules, v => `${v.name}(${v.id})`)
      .then(idx => modules[idx]);

    const docs = Memory.list('doc', user)?.filter(v => v.moduleId === module.id)!;
    const doc = await QuickPick
      .show(docs, v => `${v.name}(${v.id})`)
      .then(idx => docs[idx]);

    return doc;
  }

  export async function call(arg0: any) {
    const docItem = await getDocItemFormAny(arg0);

    if (!docItem) { return; }

    open(docItem.visitor.url + '/#/view/' + docItem.id);
  }
}

